<!-- 创建消息通知 -->
<template>
  <div class="create-notification">
    <div class="form-container">
      <div class="form-header">
        <h2>创建消息通知</h2>
        <button class="btn-secondary" @click="goBack">返回</button>
      </div>
      
      <form @submit.prevent="handleSubmit" class="notification-form">
        <!-- 通知标题 -->
        <div class="form-group">
          <label class="required">通知标题</label>
          <input 
            v-model="form.noticeTitle" 
            type="text" 
            placeholder="请输入通知标题"
            maxlength="100"
            required
          >
          <div class="char-count">{{ form.noticeTitle.length }}/100</div>
        </div>

        <!-- 通知类型 -->
        <div class="form-group">
          <label class="required">通知类型</label>
          <select v-model="form.noticeType" required>
            <option value="">请选择通知类型</option>
            <option value="system">系统消息</option>
            <option value="company">公司消息</option>
            <option value="product">产品消息</option>
            <option value="mention">@ 我的</option>
            <option value="urgent">紧急通知</option>
            <option value="announcement">公告</option>
          </select>
        </div>

        <!-- 接收人设置 -->
        <div class="form-group">
          <label>接收人设置</label>
          <div class="receiver-options">
            <label class="radio-option">
              <input 
                type="radio" 
                v-model="receiverType" 
                value="all"
                @change="handleReceiverTypeChange"
              >
              <span>全员通知</span>
            </label>
            <label class="radio-option">
              <input 
                type="radio" 
                v-model="receiverType" 
                value="specific"
                @change="handleReceiverTypeChange"
              >
              <span>指定接收人</span>
            </label>
          </div>
          
          <!-- 指定接收人选择 -->
          <div v-if="receiverType === 'specific'" class="receiver-selection">
            <div class="selected-users">
              <div 
                v-for="user in selectedUsers" 
                :key="user.id" 
                class="user-tag"
              >
                {{ user.realName || user.username }}
                <button 
                  type="button" 
                  @click="removeUser(user.id)"
                  class="remove-btn"
                >×</button>
              </div>
            </div>
            <button 
              type="button" 
              @click="showUserSelector = true"
              class="btn-secondary"
            >
              选择用户
            </button>
          </div>
        </div>

        <!-- 通知内容 -->
        <div class="form-group">
          <label class="required">通知内容</label>
          <textarea 
            v-model="form.content" 
            placeholder="请输入通知内容"
            rows="6"
            maxlength="2000"
            required
          ></textarea>
          <div class="char-count">{{ form.content.length }}/2000</div>
        </div>

        <!-- 发布设置 -->
        <div class="form-group">
          <label>发布设置</label>
          <div class="publish-options">
            <label class="radio-option">
              <input 
                type="radio" 
                v-model="form.isPublish" 
                :value="true"
              >
              <span>立即发布</span>
            </label>
            <label class="radio-option">
              <input 
                type="radio" 
                v-model="form.isPublish" 
                :value="false"
              >
              <span>保存草稿</span>
            </label>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <button type="button" @click="goBack" class="btn-secondary">取消</button>
          <button type="submit" :disabled="submitting" class="btn-primary">
            {{ submitting ? '提交中...' : (form.isPublish ? '发布通知' : '保存草稿') }}
          </button>
        </div>
      </form>
    </div>

    <!-- 用户选择弹窗 -->
    <div v-if="showUserSelector" class="modal-overlay" @click.self="closeUserSelector">
      <div class="modal user-selector-modal">
        <div class="modal-header">
          <h3>选择接收人</h3>
          <button @click="closeUserSelector" class="modal-close">×</button>
        </div>
        <div class="modal-body">
          <div class="search-box">
            <input 
              v-model="userSearchKeyword" 
              type="text" 
              placeholder="搜索用户姓名或用户名"
              @input="searchUsers"
            >
          </div>
          <div class="user-list">
            <div 
              v-for="user in filteredUsers" 
              :key="user.id" 
              class="user-item"
              :class="{ selected: isUserSelected(user.id) }"
              @click="toggleUser(user)"
            >
              <div class="user-info">
                <div class="user-name">{{ user.realName || user.username }}</div>
                <div class="user-dept">{{ user.deptName || '未分配部门' }}</div>
              </div>
              <div class="user-checkbox">
                <input 
                  type="checkbox" 
                  :checked="isUserSelected(user.id)"
                  @click.stop
                >
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="closeUserSelector" class="btn-secondary">取消</button>
          <button @click="confirmUserSelection" class="btn-primary">
            确定 (已选{{ selectedUsers.length }}人)
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { createNotice } from '@/api/notice'
import { listUsers, pageUsers } from '@/api/user'

export default {
  name: 'CreateNotification',
  data() {
    return {
      form: {
        noticeTitle: '',
        noticeType: '',
        content: '',
        publishId: null,
        receiverIds: [],
        isPublish: true
      },
      receiverType: 'all', // 'all' | 'specific'
      selectedUsers: [],
      allUsers: [],
      filteredUsers: [],
      userSearchKeyword: '',
      showUserSelector: false,
      submitting: false
    }
  },
  created() {
    this.initForm()
    this.loadUsers()
  },
  methods: {
    initForm() {
      // 从localStorage或其他方式获取当前用户ID
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
      this.form.publishId = userInfo.id || 1
    },
    
    async loadUsers() {
      try {
        // 先尝试使用listUsers获取所有用户
        let response = await listUsers()
        let users = response?.data || []
        
        // 如果listUsers返回的数据为空或格式不对，尝试使用pageUsers
        if (!Array.isArray(users) || users.length === 0) {
          response = await pageUsers({ pageNum: 1, pageSize: 1000 })
          users = response?.data?.records || response?.data || []
        }
        
        this.allUsers = users
        this.filteredUsers = users
      } catch (error) {
        console.error('加载用户列表失败:', error)
        this.$message?.error?.('加载用户列表失败')
      }
    },
    
    searchUsers() {
      if (!this.userSearchKeyword.trim()) {
        this.filteredUsers = this.allUsers
        return
      }
      
      const keyword = this.userSearchKeyword.toLowerCase()
      this.filteredUsers = this.allUsers.filter(user => {
        const name = (user.realName || user.username || '').toLowerCase()
        const dept = (user.deptName || '').toLowerCase()
        return name.includes(keyword) || dept.includes(keyword)
      })
    },
    
    handleReceiverTypeChange() {
      if (this.receiverType === 'all') {
        this.selectedUsers = []
        this.form.receiverIds = []
      }
    },
    
    isUserSelected(userId) {
      return this.selectedUsers.some(user => user.id === userId)
    },
    
    toggleUser(user) {
      const index = this.selectedUsers.findIndex(u => u.id === user.id)
      if (index > -1) {
        this.selectedUsers.splice(index, 1)
      } else {
        this.selectedUsers.push(user)
      }
    },
    
    removeUser(userId) {
      this.selectedUsers = this.selectedUsers.filter(user => user.id !== userId)
      this.form.receiverIds = this.selectedUsers.map(user => user.id)
    },
    
    closeUserSelector() {
      this.showUserSelector = false
      this.userSearchKeyword = ''
      this.filteredUsers = this.allUsers
    },
    
    confirmUserSelection() {
      this.form.receiverIds = this.selectedUsers.map(user => user.id)
      this.closeUserSelector()
    },
    
    async handleSubmit() {
      if (this.submitting) return
      
      // 表单验证
      if (!this.form.noticeTitle.trim()) {
        this.$message?.error?.('请输入通知标题')
        return
      }
      
      if (!this.form.noticeType) {
        this.$message?.error?.('请选择通知类型')
        return
      }
      
      if (!this.form.content.trim()) {
        this.$message?.error?.('请输入通知内容')
        return
      }
      
      if (this.receiverType === 'specific' && this.selectedUsers.length === 0) {
        this.$message?.error?.('请选择接收人')
        return
      }
      
      this.submitting = true
      
      try {
        const submitData = {
          ...this.form,
          receiverIds: this.receiverType === 'all' ? [] : this.form.receiverIds
        }
        
        const response = await createNotice(submitData)
        
        if (response?.code === 200 || response?.success) {
          this.$message?.success?.(this.form.isPublish ? '通知发布成功' : '草稿保存成功')
          this.$emit('success')
        } else {
          throw new Error(response?.message || '操作失败')
        }
      } catch (error) {
        console.error('创建通知失败:', error)
        this.$message?.error?.(error.message || '操作失败，请重试')
      } finally {
        this.submitting = false
      }
    },
    
    goBack() {
      this.$emit('cancel')
    }
  }
}
</script>

<style scoped>
.create-notification {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.form-container {
  max-width: 800px;
  margin: 0 auto;
  background: #fff;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.form-header h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
}

.notification-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-weight: 500;
  color: #606266;
  font-size: 14px;
}

.form-group label.required::after {
  content: ' *';
  color: #f56c6c;
}

.form-group input,
.form-group select,
.form-group textarea {
  padding: 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #409eff;
}

.char-count {
  align-self: flex-end;
  font-size: 12px;
  color: #909399;
}

.receiver-options,
.publish-options {
  display: flex;
  gap: 16px;
}

.radio-option {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
  font-weight: normal !important;
}

.radio-option input[type="radio"] {
  margin: 0;
  width: auto;
  padding: 0;
}

.receiver-selection {
  margin-top: 12px;
}

.selected-users {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 12px;
  min-height: 32px;
  padding: 8px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background: #fafafa;
}

.user-tag {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 4px 8px;
  background: #409eff;
  color: #fff;
  border-radius: 4px;
  font-size: 12px;
}

.remove-btn {
  background: none;
  border: none;
  color: #fff;
  cursor: pointer;
  font-size: 14px;
  line-height: 1;
  padding: 0;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

.btn-primary {
  background: #409eff;
  color: #fff;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.btn-primary:hover:not(:disabled) {
  background: #66b1ff;
}

.btn-primary:disabled {
  background: #c0c4cc;
  cursor: not-allowed;
}

.btn-secondary {
  background: #fff;
  color: #606266;
  border: 1px solid #dcdfe6;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.btn-secondary:hover {
  color: #409eff;
  border-color: #c6e2ff;
  background: #ecf5ff;
}

/* 用户选择弹窗样式 */
.modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.user-selector-modal {
  width: 600px;
  max-height: 80vh;
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

.modal-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.modal-close {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #909399;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-body {
  padding: 20px;
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.search-box {
  margin-bottom: 16px;
}

.search-box input {
  width: 100%;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
}

.user-list {
  flex: 1;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  max-height: 300px;
}

.user-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f5f7fa;
  cursor: pointer;
  transition: background-color 0.3s;
}

.user-item:hover {
  background: #f5f7fa;
}

.user-item.selected {
  background: #ecf5ff;
  border-color: #409eff;
}

.user-info {
  flex: 1;
}

.user-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.user-dept {
  font-size: 12px;
  color: #909399;
}

.user-checkbox input {
  margin: 0;
  padding: 0;
  width: auto;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 20px;
  border-top: 1px solid #ebeef5;
}
</style>